<template>
  <div class="shop-cart">
    <nav-bar>
      <template v-slot:center>
        <div style="font-size: 0.16rem; color: #fff">
          购物车(<span style="color: red"> {{ $store.state.cart.cartCount }} </span>)
        </div>
      </template>
    </nav-bar>

    <!-- 商品栏 -->
    <Scroll ref="myScroll" class="my-scroll">
      <template v-if="shopCartData.length">
        <van-swipe-cell v-for="(item, index) in shopCartData" :key="item.id">
          <div class="goods-cell">
            <van-checkbox
              v-model="item.is_checked"
              checked-color="#1baeae"
              :name="item.id"
              @change="checkItem"
              class="checkbox-goods"
            ></van-checkbox>
            <div class="goods-box">
              <div style="display: flex">
                <div class="left">
                  <img :src="item.goods.cover_url" alt="" />
                </div>
                <div class="center">
                  <span>{{ item.goods.title }}</span>
                  <div class="price">
                    <small>￥</small><span>{{ item.goods.price }}.00</span>
                  </div>
                </div>
              </div>
              <div class="right">
                <span>x{{ item.goods.stock }}</span>
                <div>
                  <van-stepper
                    v-model="item.num"
                    :min="1"
                    :max="item.goods.stock"
                    :name="item.id"
                    async-change
                    @change="onChange(item)"
                  />
                </div>
              </div>
            </div>
          </div>
          <template #right>
            <van-button
              square
              icon="delete"
              type="danger"
              class="delete-button"
              @click="deleteShopGoods(item, index)"
            />
          </template>
        </van-swipe-cell>
      </template>
      <!-- 空空如也 -->
      <template v-else>
        <div class="empty">
          <div>
            <img src="~assets/images/icon/empty.png" alt="" class="empty-cart" />
            <div class="title">购物车空空如也</div>
            <van-button round type="primary" block class="button" color="#1baeae" @click="$router.push('/category')">
              前往选购</van-button
            >
          </div>
        </div>
      </template>
    </Scroll>
    <!-- 底部栏 -->
    <van-submit-bar :price="totalPrice * 100" button-text="结算" @submit="onSubmit" class="submit-bar">
      <van-checkbox v-model="checkedAll" checked-color="#1baeae">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import UseTabBar from 'hooks/tabbar/UseTabBar'
import { ref, computed, watchEffect } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { Toast } from 'vant'
import { dubounce } from '@/utils/utils.js'
import useScroll from 'hooks/scroll/useScroll'
import Scroll from 'components/common/scroll/Scroll.vue'
import { getCart, modifyCart, checkedCart, deleteCartItem } from 'network/cart'
export default {
  components: { Scroll },
  name: 'Shopcart',
  setup() {
    UseTabBar()
    // 生成路由实例
    const router = useRouter()
    //生成store实例
    const store = useStore()
    // 获取scroll实例
    let myScroll = ref(null)
    // 监视scroll hooks
    useScroll(myScroll)
    // 商品数据
    let shopCartData = ref([])
    // 定义一个全选的计算属性
    let checkedAll = computed({
      get() {
        // 书本中有一个没有被选中就让全选为false
        return !shopCartData.value.find(item => item.is_checked !== true)
      },
      set(val) {
        // 所有的书本跟随全选按钮的变化
        shopCartData.value.forEach(item => (item.is_checked = val))
      }
    })
    // 定义一个所有价格的计算属性
    let totalPrice = computed(() => {
      // 先过滤出来所有选中的
      const checkedGoods = shopCartData.value.filter(item => item.is_checked)
      // 所有选中的价格的总和
      return checkedGoods.reduce((prev, item) => {
        return (prev = item.num * item.goods.price + prev)
      }, 0)
    })
    // 改变服务器中商品的选中状态
    const checkItem = () => {
      const changeArr = shopCartData.value.filter(item => item.is_checked).map(item => item.id)
      checkedCart({ cart_ids: changeArr })
    }
    Toast.loading({
      message: '加载中...',
      forbidClick: true
    })
    getCart('include=goods')
      .then(({ data }) => {
        data.forEach(item => {
          item.is_checked = item.is_checked === 1 ? true : false
        })
        shopCartData.value = data
        // 清除轻提示
        Toast.clear()
      })
      .catch(err => {
        console.log(err)
      })
    // 更新服务器商品数量的数据
    const changeShopNum = detail => {
      modifyCart(detail.id, { num: detail.num })
    }
    // 删除商品的回调函数
    const deleteShopGoods = ({ id }, index) => {
      // 服务器更新删除的数据
      deleteCartItem(id).then(res => {
        if (res.status === 204) {
          Toast.success('删除成功!')
        }
        // 更新购物车的种类数量
        store.dispatch('cart/updateCart')
      })

      // 页面删除
      shopCartData.value.splice(index, 1)
    }
    // 异步改变购物车的数量
    // 实现防抖
    const onChange = dubounce(changeShopNum, 500)
    // 定义一个提交订单的回调
    const onSubmit = () => {
      if (shopCartData.value.every(item => item.is_checked === false)) return Toast.fail('请选择商品')
      router.push('/createorder')
    }
    // 只要总价发生改变就改变Vuex中的总价
    watchEffect(() => {
      store.commit('order/GETORDERTOTALPRICE', totalPrice)
    })
    return {
      checkedAll,
      onSubmit,
      shopCartData,
      myScroll,
      onChange,
      totalPrice,
      checkItem,
      deleteShopGoods,
      store,
      router
    }
  }
}
</script>

<style lang="scss" scoped>
.shop-cart {
  .goods-card {
    margin: 0;
    background-color: #fff;
  }

  .delete-button {
    height: 100%;
  }
  .goods-cell {
    display: flex;
    padding: 15px;

    .goods-box {
      display: flex;
      flex: 1;
      justify-content: space-between;
    }
    .left,
    .center,
    .right {
      display: flex;
      flex-direction: column;
    }
    .left {
      img {
        height: 0.8rem;
        width: 0.8rem !important;
        border-radius: 0.05rem;
      }
    }

    .center,
    .right {
      padding: 0.1rem 0;
      justify-content: space-between;
    }
    .right {
      align-items: flex-end;
    }
    .price {
      color: red;
    }
  }
  .empty {
    height: 60vh;
    width: 100vw;
    display: flex;
    justify-content: center;
    align-items: center;
    div {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      font-size: 0.12rem;
      .empty-cart {
        height: 1rem;
        width: 1rem !important;
        margin-bottom: 0.1rem;
      }
      .title {
        margin-bottom: 0.2rem;
      }
      .button {
        height: 0.3rem;
        width: 1.5rem;
      }
    }
  }
  .my-scroll {
    height: calc(100vh - 0.44rem - 0.52rem);
  }
  .submit-bar {
    height: 0.52rem;
  }
}
::v-deep(.van-checkbox) {
  margin-right: 0.1rem;
}
</style>